/**
 *     行为捕捉收集代码 [当前版本   1.0]
 *     author:jack
 */
(function () {
    var transferParams = {}, //PV/UV请求JSON参数对象
        config = {
            dm: ["http://localhost:8989/"]//修改域名
			, id: "7787x900kkdk8skfjkkl3kljl", //站点ID
			},
      ucsparms = {};
    ucsparms.la = function () { //FALSH支持版本
        var a = "";
        if (navigator.plugins && navigator.mimeTypes.length) {
            var b = navigator.plugins["Shockwave Flash"];
            b && b.description && (a = b.description.replace(/^.*\s+(\S+)\s+\S+$/, "$1"))
        } else if (window.ActiveXObject) try {
            if (b = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"))(a = b.GetVariable("$version")) && (a = a.replace(/^.*\s+(\d+),(\d+).*$/, "$1.$2"))
        } catch (e) {
        }
        return a;
    };
    /**发送PV的get请求参数**/
    config.httpparms = {};
    config.httpparms.ua = encodeURIComponent(navigator.userAgent); //    /msie(\d+\.\d+)/i.test(navigator.userAgent);
    config.httpparms.cookieEnabled = navigator.cookieEnabled;
    config.httpparms.javaEnabled = navigator.javaEnabled();
    config.httpparms.language = navigator.language || navigator.browserLanguage || navigator.systemLanguage || navigator.userLanguage || "";
    config.httpparms.ya = (window.screen.width || 0) + "x" + (window.screen.height || 0);
    config.httpparms.colorDepth = window.screen.colorDepth || 0; //颜色分辨率
    config.cookie = {};
    config.httpparms.su = document.referrer || ""; //上一页
    config.httpparms.vi = "1.0.1"; //js版本
    config.httpparms.fl = ucsparms.la();
    config.httpparms.stag = "pv_stag"; //标签
    config.httpparms.tt = ""; //网页标题
    config.httpparms.nu = window.location.href || ""; //当前页
    config.httpparms.sid = ""; //用户ID


    /**
     随机ID生成
     **/
    var CHARS = '0123456789abcdefghijklmnopqrstuvwxyz'.split('');
    Math.uuidFast = function () {
        var chars = CHARS,
            uuid = new Array(36),
            rnd = 0,
            r;
        for (var i = 0; i < 36; i++) {
            if (i == 8 || i == 13 || i == 18 || i == 23) {
                uuid[i] = '';
            } else if (i == 14) {
                uuid[i] = '4';
            } else {
                if (rnd <= 0x02) rnd = 0x2000000 + (Math.random() * 0x1000000) | 0;
                r = rnd & 0xf;
                rnd = rnd >> 4;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
        return uuid.join('');
    };

    /** START  工具类**/
    var kcUtils = {
        /**
         * v1.3 需求时间格式化
         * **/
        Format: function (fmt) { //author: meizz
            var date = new Date();
            var o = {
                "M+": date.getMonth() + 1, //月份
                "d+": date.getDate(), //日
                "h+": date.getHours(), //小时
                "m+": date.getMinutes(), //分
                "s+": date.getSeconds(), //秒
                "q+": Math.floor((date.getMonth() + 3) / 3), //季度
                "S": date.getMilliseconds() //毫秒
            };
            if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
            return fmt;
        },
        getBorTitle:function(){
             //获取网页标题 ，有些页面可能为空
            if(document.getElementsByTagName("title")[0]!=null){
                return encodeURI(document.title||document.getElementsByTagName("title")[0].text || "")
            }
            kcUtils.encodeURI(document.title || "");

        },
        setCookie: function (name, value) {
            var Days = 30;
            var exp = new Date();
            exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
            document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();
        },
        getCookie: function (name) { //取出cookie里的value
            var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
            // if (arr = document.cookie.match(reg) & arr != undefined) TODO 有问题
            if (arr = document.cookie.match(reg))
                return unescape(arr[2]);
            else
                return null;
        },
        randomChar: function (l) { //生成随机数rnd
            var x = "0123456789";
            var tmp = "";
            var timestamp = new Date().getTime();
            for (var i = 0; i < l; i++) {
                tmp += x.charAt(Math.ceil(Math.random() * 100000000) % x.length);
            }
            return timestamp + tmp;
        },
        genCti: function () {
            try {
                var cti = this.getCookie("cti");
                //生成用户
                if (cti != null) { //如果存在就返回，不存在就生成
                    return cti;
                } else {
                    /** 随机生成6位数字 **/
                    var aNum = "";
                    for (var i = 0; i < 6; i++) {
                        aNum += Math.floor(Math.random() * 10);
                    }
                    /** 返回时间分区加6位数字 **/
                    var ctid = kcUtils.Format("yyyyMMddhhmmss") + aNum;
                    this.setCookie("cti", ctid);
                    return ctid;
                }
            } catch (e) {

            }
        },
        genBid: function () {
            try {
                var bid = this.getCookie("bid");
                //生成用户
                if (bid != null) { //如果存在就返回，不存在就生成
                    return bid;
                } else {
                    var uubid = Math.uuidFast();
                    this.setCookie("bid", uubid)
                    return uubid;
                }
            } catch (e) {

            }
        },
        randrom: function () { //生成随机数
            return Math.random() * 100000000000000000;
        },
        lastTime: function () { //生成当前时间戳
            return new Date().getTime();
        },
        encodeURI: function (x) {
            try {
                return encodeURIComponent(encodeURIComponent(x));
            } catch (e) {
            }
        }
    };

    /** END  工具类**/

    /**
     * AJAX请求工具
     * TODO 要解决IE的问题
     */
    var AjaxUtil = {

        // 基础选项
        options: {
            method: "get", // 默认提交的方法,get post
            url: "", // 请求的路径 required
            params: {}, // 请求的参数
            type: 'text', // 返回的内容的类型,text,xml,json
            callback: function () {
            } // 回调函数 required
        },

        //发送get请求
        request: function (options) {
            var ajaxObj = this;
            // 设置参数
            ajaxObj.setOptions.call(ajaxObj, options);
            // 格式化参数
            var formateParams = ajaxObj.formateParameters.call(ajaxObj);
            var url = ajaxObj.options.url;
            ajaxObj.getImage(url, formateParams, null);
        },


        /*
         * request是 字符串  ab=22&eeee=22
         * Send image request to Piwik server using GET.
         * The infamous web bug (or beacon) is a transparent, single pixel (1x1) image
         */
        getImage: function (url, request, callback) {
            var image = new Image(1, 1);
            image.onload = function () {
                iterator = 0; // To avoid JSLint warning of empty block
                if (typeof callback === 'function') {
                    callback();
                }
            };
            image.src = url + (url.indexOf('?') < 0 ? '?' : '&') + request;
        },

        // 设置基础选项
        setOptions: function (newOptions) {
            for (var pro in newOptions) {
                this.options[pro] = newOptions[pro];
            }
        },
        // 格式化请求参数
        formateParameters: function () {
            var paramsArray = [];
            var params = this.options.params;
            for (var pro in params) {
                var paramValue = params[pro];
                paramsArray.push(pro + "=" + paramValue);
            }
            return paramsArray.join("&");
        }
    };
    /**END   AJAX 工具类**/


    /**
     * 1._hmt对象赋值的一些事
     * 2. 一些参数初始化
     */
    (function () {
        /**
         *     _bct 对象操作，用户传入自定义参数
         */
        window._bct = {
            account: config.id,
            push: function (args) {
                if (args[0] != null && (typeof args[0] == "string")) {
                    /** TODO 判断是否为空，用正则判断是否符合规范  ***/
                    if (args[0] === "_trackPageview") {
                        //判断是否有_setAccount变量
                        if (kcUtils.getCookie("_setAccount") != null) { // TODO &&是指定规则的账号
                            config.id = kcUtils.getCookie("_setAccount");
                        }
                        transferParams.cti = kcUtils.genCti();//时间分区
                        transferParams.bid = kcUtils.genBid(); //用户ID
                        transferParams.rnd = kcUtils.randrom(); //随机数
                        transferParams.lt = kcUtils.lastTime(); //最当前访问时间
                        //参数收集
                        transferParams.ds = config.httpparms.ya;
                        transferParams.cl = config.httpparms.colorDepth + "-bit";
                        transferParams.tt = kcUtils.getBorTitle();
                        transferParams.su = kcUtils.encodeURI(config.httpparms.su);
                        transferParams.vi = config.httpparms.vi; //js版本
                        transferParams.ck = config.httpparms.cookieEnabled;
                        transferParams.ln = config.httpparms.language;
                        transferParams.ja = config.httpparms.javaEnabled;
                        transferParams.fl = config.httpparms.fl;
                        transferParams.si = config.id;
                        transferParams.stag = config.httpparms.stag;
                        transferParams.sb = ""; //保留字段，是否是360浏览器
                        transferParams.ua = config.httpparms.ua;
                        transferParams.nu = kcUtils.encodeURI(config.httpparms.nu);
                        transferParams.sid = kcUtils.getCookie("_setLoginId") || "";
                        //发送捕捉
                        AjaxUtil.request({
                            url: config.dm[0] + "hm.gif",
                            params: JSON.parse(JSON.stringify(transferParams)),
                            method: 'get'
                        });

                    }

                    //事件跟踪
                    if (args[0] === "_trackEvent") {
                        var _track = {}; //TODO 参数要不要支持 中文 ？ 支持
                        _track.cti = kcUtils.genCti();
                        _track.ct = kcUtils.encodeURI(args[1]); //要监控的目标的类型名称
                        _track.at = kcUtils.encodeURI(args[2]); //用户跟目标交互的行为
                        _track.kl = kcUtils.encodeURI(args[3]); //事件的一些额外信息可选
                        _track.vl = kcUtils.encodeURI(args[4]); //事件的一些数值信息，比如权重、时长、价格等等 可选
                        _track.lt = kcUtils.lastTime(); //最当前访问时间
                        _track.sid = kcUtils.getCookie("_setLoginId") || "";
                        _track.tag = "_trackEvent"; //用户标签
                        _track.bid = kcUtils.genBid(); //用户ID
                        _track.rnd = kcUtils.randrom(); //随机数
                        _track.lt = kcUtils.lastTime(); //最当前访问时间
                        _track.ds = config.httpparms.ya;
                        _track.cl = config.httpparms.colorDepth + "-bit";
                        _track.tt = kcUtils.getBorTitle();
                        _track.su = kcUtils.encodeURI(config.httpparms.su);
                        _track.vi = config.httpparms.vi; //js版本
                        _track.ck = config.httpparms.cookieEnabled;
                        _track.ln = config.httpparms.language;
                        _track.ja = config.httpparms.javaEnabled;
                        _track.fl = config.httpparms.fl;
                        _track.si = config.id;
                        _track.stag = config.httpparms.stag;
                        _track.sb = ""; //保留字段，是否是360浏览器
                        _track.ua = config.httpparms.ua;
                        _track.nu = kcUtils.encodeURI(config.httpparms.nu);
                        //发送跟踪
                        AjaxUtil.request({
                            url: config.dm[0] + "hm.gif",
                            params: JSON.parse(JSON.stringify(_track)),
                            method: 'get'
                        });

                    }

                    //设置是否自动PV
                    if (args[0] === "_setAutoPageview") {
                        try {
                            if (args[1] === false) {
                                kcUtils.setCookie("_setAutoPageview", false); //设置自动PV为false
                            } else {
                                kcUtils.setCookie("_setAutoPageview", true);
                            }
                        } catch (e) {

                        }
                    }
                    //设置站点ID
                    if (args[0] === "_setAccount") {
                        try {
                            config.id = args[1]; //此处要用正刚验证
                            kcUtils.setCookie("_setAccount", args[1]);
                            //								console.log(config.id);
                        } catch (e) {
                        }
                    }

                    //设置登录用户的Id
                    if (args[0] === "_setLoginId") {
                        try {
                            config.httpparms.sid = args[1]; //此处要用正刚验证
                            kcUtils.setCookie("_setLoginId", args[1]);
                        } catch (e) {
                        }
                    }
                }
            }
        }


    })();


    /**
     TODO 页面初始化时，自动PV/ 以及页面退出时候发PV、支持常用浏览器
     自动执行
     ***/
    (function () {
        var bc_init = {
            init: function () {

                //判断是否有_setAccount变量
                if (kcUtils.getCookie("_setAccount") != null) { //TODO &&是指定规则的站点账号
                    config.id = kcUtils.getCookie("_setAccount");
                }
                transferParams.cti = kcUtils.genCti()//时间分区
                transferParams.bid = kcUtils.genBid(); //用户ID
                transferParams.rnd = kcUtils.randrom(); //随机数
                transferParams.lt = kcUtils.lastTime(); //最当前访问时间
                //参数收集
                transferParams.ds = config.httpparms.ya;
                transferParams.cl = config.httpparms.colorDepth + "-bit";
                transferParams.tt = kcUtils.getBorTitle();
                //JS是两次编码URL,后端解码
                transferParams.su = kcUtils.encodeURI(config.httpparms.su);
                transferParams.vi = config.httpparms.vi; //js版本
                transferParams.ck = config.httpparms.cookieEnabled;
                transferParams.ln = config.httpparms.language;
                transferParams.ja = config.httpparms.javaEnabled;
                transferParams.fl = config.httpparms.fl;
                transferParams.si = config.id;
                transferParams.stag = config.httpparms.stag;
                transferParams.sb = ""; //是否是360浏览器
                transferParams.ua = config.httpparms.ua;
                transferParams.nu = kcUtils.encodeURI(config.httpparms.nu);
                transferParams.sid = kcUtils.getCookie("_setLoginId") || "";
                transferParams.jsonp = "callback";


                //判断是否禁用自动PV
                if (kcUtils.getCookie("_setAutoPageview") === null || kcUtils.getCookie("_setAutoPageview") === "true") {
                    //pv/uv统计请求
                    AjaxUtil.request({
                        url: config.dm[0] + "hm.gif",
                        params: JSON.parse(JSON.stringify(transferParams)),
                        method: 'get'
                    });


                }

                /** 浏览器页面退出事件，**/
                try {
                    window.addEventListener("beforeunload", function (event) {
                        transferParams.stag = "leave_stag";
                        transferParams.nu = kcUtils.encodeURI(window.location.href || "");
                        AjaxUtil.request({
                            url: config.dm[0] + "hm.gif",
                            params: JSON.parse(JSON.stringify(transferParams)),
                            method: 'get'
                        });
                    });
                } catch (e) {
                }

            }
        };

        //执行服务初始化
        bc_init.init();


    })();


})();

